'use strict';

const Controller = require('egg').Controller;

class loginjwt extends Controller {
  async login() {
    const { ctx, app } = this;
    const { username, password } = ctx.request.body;
    console.log(username, password);
    const userInfo = await ctx.service.jwt.getUserByName(username);
    if (!userInfo || !userInfo.id) {
      ctx.body = {
        code: 500,
        msg: '账号不存在',
        success: false,
        data: null,
      };
      return;
    }
    if (userInfo && password !== userInfo.password) {
      ctx.body = {
        code: 500,
        msg: '账号密码错误',
        success: false,
        data: null,
      };
      return;
    }
    // token 生成
    const token = app.jwt.sign(
      {
        id: userInfo.id,
        username: userInfo.username,
        exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60, // token 有效期为 24 小时
      },
      app.config.jwt.secret
    );
    ctx.body = {
      code: 200,
      message: '登录成功',
      success: true,
      data: {
        token,
      },
    };
  }
}
module.exports = loginjwt;
